package com.wyclabs.cardmaker;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import java.util.ResourceBundle;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.jfoenix.controls.JFXButton;
import com.rnkrsoft.bopomofo4j.Bopomofo4j;
import com.wyclabs.cardmaker.cells.EditingCell;
import com.wyclabs.cardmaker.cells.LevelCell;
import com.wyclabs.cardmaker.cells.NameCell;
import com.wyclabs.cardmaker.constants.CardType;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.image.Image;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * @author TylerW
 * @date 06/18/21 1:50 PM
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class MainPaneController extends CommonController implements Initializable {
    public static final String name = "mainPane";
    @FXML
    private JFXButton btnImport;
    @FXML
    private JFXButton btnCreate;
    @FXML
    private JFXButton btnAddLine;
    @FXML
    private JFXButton btnSetting;
    @FXML
    private JFXButton btnTemplate;
    @FXML
    private TableView<Card> tableView;
    @FXML
    private TableColumn<Card, String> colName;
    @FXML
    private TableColumn<Card, String> colType;
    @FXML
    private TableColumn<Card, String> colLv;
    @FXML
    private TableColumn<Card, String> colCost;
    @FXML
    private TableColumn<Card, String> colAtk;
    @FXML
    private TableColumn<Card, String> colHp;
    @FXML
    private TableColumn<Card, String> colTag;
    @FXML
    private TableColumn<Card, String> colPath;
    @FXML
    private TableColumn<Card, String> colDesc;

    public void importExcel() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("excel", "*.xlsx", "*.xls"));
        File file = fileChooser.showOpenDialog(new Stage());
        ExcelReader reader = ExcelUtil.getReader(file);
        Sheet sheet = reader.getSheet();
        CommonService.selectedCamp = sheet.getSheetName();
        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            Card item = new Card(sheet.getRow(i));
            if (StringUtils.isBlank(item.getName().getValue())) {
                continue;
            }

            String name = item.getName().getValue();
            String cnName = null;
            Properties config = CommonService.config;
            if (Boolean.parseBoolean(config.getProperty("auto_name"))) {
                cnName = Bopomofo4j.pinyin(name, 2, false, false, "");
            }
            if (CardType.CREATURE.getType().equals(item.getType().getValue())) {
                item.setPath(new SimpleStringProperty(config.getProperty("creature_prefix") + cnName));
            } else if (CardType.MAGIC.getType().equals(item.getType().getValue())) {
                item.setPath(new SimpleStringProperty(config.getProperty("magic_prefix") + cnName));
            } else {
                item.setPath(new SimpleStringProperty(config.getProperty("hero_prefix") + cnName));
            }

            tableView.getItems().add(item);
        }
    }

    public void addLine() {
        tableView.getItems().add(new Card("", "", "", "", "", "", "", "", ""));
    }

    public void copyTemplate() throws IOException {
        File file = CommonService.readResource("resource/template.xlsx");
        if (file.exists()) {
            Desktop.getDesktop().open(file);
        }
    }

    public void setting() throws IOException {
        if (!CommonService.controllers.containsKey(SettingController.name)) {
            Parent layout = FXMLLoader.load(Objects.requireNonNull(getClass().getClassLoader().getResource("fxml/config.fxml")));
            Stage popupStage = new Stage();
            popupStage.initModality(Modality.APPLICATION_MODAL);
            popupStage.setScene(new Scene(layout));
            popupStage.setTitle("设置");
            popupStage.getIcons().add(new Image(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("ico.jpg"))));
            popupStage.show();
        } else {
            CommonController controller = CommonService.controllers.get(SettingController.name);
            Stage window = controller.getRootStage();
            window.show();
        }
    }

    public void export() throws IOException {
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setTitle("选择导出目录");
        File file = chooser.showDialog(new Stage());
        CommonService.selectedFolder = file.getPath();
        for (Card item : tableView.getItems()) {
            if (StringUtils.isBlank(item.getPath().getValue())) {
                continue;
            }
            String path = item.getPath().getValue();
            File folder = FileUtil.mkdir(file.getPath() + File.separator + path);
            CardGenerator.createCard(item, folder);
        }
        Alert alert = new Alert(Alert.AlertType.NONE, "导出成功！", new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setTitle("提示");
        alert.showAndWait();
        Desktop.getDesktop().open(file);
    }

    @SneakyThrows
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colName.setCellValueFactory(cellData -> cellData.getValue().getName());
        colName.setCellFactory(p -> new NameCell());

        colType.setCellValueFactory(cellData -> cellData.getValue().getType());
        colType.setCellFactory(p -> new EditingCell());

        colLv.setCellValueFactory(cellData -> cellData.getValue().getLv());
        colLv.setCellFactory(p -> new LevelCell());

        colCost.setCellValueFactory(cellData -> cellData.getValue().getCost());
        colCost.setCellFactory(p -> new EditingCell());

        colAtk.setCellValueFactory(cellData -> cellData.getValue().getAtk());
        colAtk.setCellFactory(p -> new EditingCell());

        colHp.setCellValueFactory(cellData -> cellData.getValue().getHp());
        colHp.setCellFactory(p -> new EditingCell());

        colTag.setCellValueFactory(cellData -> cellData.getValue().getTag());
        colTag.setCellFactory(p -> new EditingCell());

        colPath.setCellValueFactory(cellData -> cellData.getValue().getPath());
        colPath.setCellFactory(p -> new EditingCell());

        colDesc.setCellValueFactory(cellData -> cellData.getValue().getDesc());
        colDesc.setCellFactory(p -> new EditingCell());

        tableView.setEditable(true);
        CommonService.controllers.put(name, this);

        Properties prop = new Properties();
        prop.load(CommonService.readAsResource("resource/config.properties"));

        CommonService.config = prop;

    }
}
